 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  GameViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#import "GameViewController.h"
#import "AppDelegate.h"
#import "PlayerInfo.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface GameViewController ()
@property(nonatomic, retain) PlayerManagerViewController * playerManagerViewController;
@property(nonatomic, retain) GameControlViewController * gameControlViewController;
@property(nonatomic, retain) TableManagerViewController * tableManagerViewController;
@property(nonatomic, retain) GameOverViewController * gameOverViewController;
@property(nonatomic, retain) TableClockViewController * tableClockViewController;
@property(nonatomic, retain) GameRuleProxy * gameRuleProxy;

@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation GameViewController
@synthesize playerManagerView = _playerManagerView;
@synthesize gameControlView = _gameControlView;
@synthesize tableMangagerView = _tableMangagerView;
@synthesize playerManagerViewController =_playerManagerViewController;
@synthesize gameControlViewController = _gameControlViewController;
@synthesize tableManagerViewController = _tableManagerViewController;
@synthesize gameOverView =_gameOverView;
@synthesize gameOverViewController =_gameOverViewController;
@synthesize tableClockView = _tableClockView;
@synthesize tableClockViewController = _tableClockViewController;
@synthesize gameRuleProxy = _gameRuleProxy;
@synthesize autoplay = _autoplay;
@synthesize myPlayer;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PlayerInfo * rivalPlayer;
NSString * dealer;
NSString * smallblind;
NSString * bigblind;
bool isShowControl;
long callMoney;
long BBMoney;
static GameViewController* instance;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Game Rule Proxy Delegate
-(void) startGameCallback:(NSMutableDictionary*) data
{
    rivalPlayer = (PlayerInfo *)[data objectForKey:@"rivalPlayer"];
    myPlayer = (PlayerInfo *)[data objectForKey:@"myPlayer"];
    [self.playerManagerViewController updateInfo:data];
}
-(void) startRoundCallback:(NSMutableDictionary*) data
{
    [btnExit setHidden:YES];
    dealer = (NSString *)[data objectForKey:@"dealer"];
    smallblind = (NSString *)[data objectForKey:@"smallblind"];
    bigblind = (NSString *)[data objectForKey:@"bigblind"];
    
    long SB = strtol([(NSString *)[data objectForKey:@"SB"] UTF8String], NULL, 0);
    BBMoney = SB*2;
    NSArray * myCards = (NSArray *)[data objectForKey:@"mycards"];
    NSArray * rivalCards = (NSArray *)[data objectForKey:@"rivalcards"];
    
    if(dealer == myPlayer.Username)
    {
        [self.playerManagerViewController subMyPlayerAni:SB];
        [self.playerManagerViewController subRivalPlayerAni:SB*2];
        [self.tableManagerViewController addMoney:SB*3];
        [self.playerManagerViewController updateMyDealer];
        [self.tableManagerViewController deal2CardTurn:rivalCards myCards:myCards dealer:true];
    }
    else 
    {
        [self.playerManagerViewController subMyPlayerAni:SB*2];
        [self.playerManagerViewController subRivalPlayerAni:SB];
        [self.tableManagerViewController addMoney:SB*3];
        [self.playerManagerViewController updateRivalDealer];
        [self.tableManagerViewController deal2CardTurn:rivalCards myCards:myCards dealer:false];
    }
}
-(void) requestStatusCallback:(NSMutableDictionary*) data
{
    long status = strtol([(NSString *)[data objectForKey:@"status"] UTF8String], NULL,0);
    
    switch (status) {
        case rNextStep:
        {     
          
            NSArray * turnCard = (NSArray *)[data objectForKey:@"turncards"];
            long turn = strtol([(NSString *)[data objectForKey:@"step"] UTF8String], NULL,0);
            isShowControl = false; // auto call requestStatus
            NSLog(@"** NextStep ** Turn is %ld", turn);
            switch (turn)
            {
                case stepTurn3Card:
                    [self.tableManagerViewController dealFlopTurn:turnCard];
                    break;
                case stepTurnCard:
                    [self.tableManagerViewController dealTurnTurn:turnCard];
                    break;
                case stepRiverCard:
                    [self.tableManagerViewController dealRiverTurn:turnCard];
                    break;
                case stepEndCard:
                    [self.tableManagerViewController dealEndTurn];
                    [self.gameRuleProxy endRound];
                    break;
                default:
                    break;
            }
        }
        break;
        case rMyControl:
        {
            //NSLog(@"** MyControl ** ");
            if(myPlayer.Money <= 0 || rivalPlayer.Money <=0)
            {
                [self performSelector:@selector(raiseHandler:) withObject:0 afterDelay:2];
            }
            else if(_autoplay)
            {
                [self performSelector:@selector(checkHandler:) withObject:false afterDelay:2];
            }
            else 
            {
                NSString* cCheck =  (NSString*) [data objectForKey:@"mAllowCheck"];
                if(cCheck == @"TRUE")
                {
                    [self.gameControlViewController updateControlBar:true];
                }
                else 
                {
                    [self.gameControlViewController updateControlBar:false];
                }
                [self.gameControlViewController show];
            }
        }
        break;
        case rRivalControl:
        {
            [self.tableClockViewController hide];
            long control =  strtol([(NSString *)[data objectForKey:@"control"] UTF8String], NULL,0);
            long money =  strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL,0);
            callMoney = money;
            switch (control) {
                case cCall:
                    if(money > 0)
                    {
                        [self.playerManagerViewController controlRivalPlayerAni:@"CALL"];
                        [self.playerManagerViewController subRivalPlayerAni:money];
                        [self.tableManagerViewController addMoney:money]; 
                        NSLog(@"** RivalControl ** CALL ** Money is %ld", money);
                    }
                    [self.gameRuleProxy requestStatus];
                    break;
                case cCheck:
                    [self.playerManagerViewController controlRivalPlayerAni:@"CHECK"];
                     NSLog(@"** RivalControl ** CHECK **");
                    [self.gameRuleProxy requestStatus];
                    break;
                case cRaise:
                    if(money > 0)
                    {
                        [self.playerManagerViewController controlRivalPlayerAni:@"RAISE"];
                        [self.playerManagerViewController subRivalPlayerAni:money];
                        [self.tableManagerViewController addMoney:money]; 
                        NSLog(@"** RivalControl ** RAISE ** Money is %ld", money);
                    }
                    [self.gameRuleProxy requestStatus];
                    break;
                case cFold:
                    [self.playerManagerViewController controlRivalPlayerAni:@"FOLD"];
                    long money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
                    long returnmoney = strtol([(NSString *)[data objectForKey:@"returnmoney"] UTF8String], NULL, 0);
                    if(returnmoney > 0) 
                    {
                        [self.playerManagerViewController addRivalPlayerAni:returnmoney];
                    }
                    
                    [self.playerManagerViewController addMyPlayerAni:money];
                    [self.gameOverViewController changeMessage:@"You Win !"];
                    [self.tableManagerViewController addMoney:0];
                    [self performSelector:@selector(showEndRoundPopup) withObject:nil afterDelay:2];
                     NSLog(@"** RivalControl ** FOLD ** Money is %ld, ReturnMoney is %ld", money, returnmoney);
                    break;
                default:
                    break;
            }
        }
        break;
        case rCheckControl:
        {
             NSLog(@"** CheckControl **");
            [self.gameRuleProxy requestStatus];
            
        }
        break;
        default:
            break;
    }
}
-(void) doActionCallback:(NSMutableDictionary*) data
{
    long action =  strtol([(NSString *)[data objectForKey:@"action"] UTF8String], NULL,0);
    long money;
    long returnmoney;
    switch (action) {
        case cCall:
            money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
            if(money > 0)
            {
                [self.playerManagerViewController subMyPlayerAni:money];
                [self.tableManagerViewController addMoney:money]; 
            }
             NSLog(@"** MyControl ** CALL ** Money is %ld", money);
            [self.gameRuleProxy requestStatus];
            break;
         case cRaise:   
            money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
            if(money > 0)
            {
                [self.playerManagerViewController subMyPlayerAni:money];
                [self.tableManagerViewController addMoney:money]; 
            }
             NSLog(@"** MyControl ** RAISE ** Money is %ld", money);
            [self.gameRuleProxy requestStatus];
            break;
        case cFold:
            money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
            returnmoney = strtol([(NSString *)[data objectForKey:@"returnmoney"] UTF8String], NULL, 0);
            if(returnmoney > 0) 
            {
                [self.playerManagerViewController addMyPlayerAni:returnmoney];
            }
            
            [self.playerManagerViewController addRivalPlayerAni:money];
            [self.gameOverViewController changeMessage:@"Fold Card !"];
            [self.tableManagerViewController addMoney:0];
             NSLog(@"** MyControl ** FOLD ** Money is %ld, Return is %ld", money, returnmoney);
            [self performSelector:@selector(showEndRoundPopup) withObject:nil afterDelay:2];
            break;
        case cCheck:
            NSLog(@"** MyControl ** CHECK **");
            [self.gameRuleProxy requestStatus];
            break;
        default:
            break;
    }
}
-(void) endRoundCallback:(NSMutableDictionary*) data
{
    long money;
    long returnmoney;
    NSString * resultStr = (NSString*) [data objectForKey:@"result"];
    if(resultStr == @"win")
    {
        money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
        returnmoney = strtol([(NSString *)[data objectForKey:@"returnmoney"] UTF8String], NULL, 0);
        if(returnmoney > 0) 
        {
             [self.playerManagerViewController addRivalPlayerAni:returnmoney];
        }
        [self.playerManagerViewController addMyPlayerAni:money];
        [self.gameOverViewController changeMessage:@"You Win !"];
        [self.tableManagerViewController animationWinPlayer:(NSArray*) [data objectForKey:@"bestCard"]];
    }
    else if (resultStr == @"lose")
    {
        money = strtol([(NSString *)[data objectForKey:@"money"] UTF8String], NULL, 0);
        returnmoney = strtol([(NSString *)[data objectForKey:@"returnmoney"] UTF8String], NULL, 0);
        if(returnmoney > 0) 
        {
            [self.playerManagerViewController addMyPlayerAni:returnmoney];
        }

        [self.playerManagerViewController addRivalPlayerAni:money];
        [self.gameOverViewController changeMessage:@"You Lose !"];
        [self.tableManagerViewController animationClosePlayer:(NSArray*) [data objectForKey:@"bestCard"]];
    }
    else {
        money = strtol([(NSString *)[data objectForKey:@"rivalmoney"] UTF8String], NULL, 0);
        [self.playerManagerViewController addRivalPlayerAni:money];
        money = strtol([(NSString *)[data objectForKey:@"mymoney"] UTF8String], NULL, 0);
        [self.playerManagerViewController addMyPlayerAni:money];
        [self.gameOverViewController changeMessage:@"You Equal !"];
        [self.tableManagerViewController animationWinPlayer:(NSArray*) [data objectForKey:@"myBestCard"]];
    }
    
    [self.tableManagerViewController addMoney:0];
    [self performSelector:@selector(showEndRoundPopup) withObject:nil afterDelay:2];
}
-(void) showEndRoundPopup
{
     if(!_autoplay) [btnExit setHidden:NO];
     [self.gameOverViewController showEndRoundAnimation];
}
-(void) endGameCallback:(NSMutableDictionary*) data
{
    // TODO: will implement later
    [self.tableManagerViewController clearCards];
    [self.gameControlViewController hide];
    [self.gameOverView setHidden:YES];
    [[AppDelegate sharedController] showMainScreen];
}
-(void) exitGameCallback:(NSMutableDictionary*) data
{
    // TODO: will implement later
    [self.tableManagerViewController clearCards];
    [self.gameControlViewController hide];
    [self.gameOverView setHidden:YES];
    [[AppDelegate sharedController] showMainScreen];
}
-(void) showTimerCallback
{
    [self.tableClockViewController show];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Exit view handler
-(IBAction) exitGameHandler:(id)sender
{
    /*[self.tableManagerViewController clearCards];
    [self.gameControlViewController hide];
    [self.gameOverView setHidden:YES];
    [[AppDelegate sharedController] showMainScreen];*/
    [self.gameRuleProxy exitGame];
}
//Exit view handler
-(IBAction) autoPlayHandler:(id)sender
{
    _autoplay = !_autoplay;
    if(_autoplay)
    {
        [btnAutoPlay setTitle:@"Control" forState:UIControlStateNormal];
    }
    else {
        [btnAutoPlay setTitle:@"Auto" forState:UIControlStateNormal];
    }
}
// PlayerManagerDelegate
-(void) playerAnimationComplete
{
    //
    NSLog(@"================ Frist Call Start Round ==================");
    [self.tableManagerViewController startRound]; // is called first
    [self.gameRuleProxy startRound];
}
// TableManagerDelegate
-(void) endRound
{
    //[self.gameOverViewController changeMessage:@"You Win !"];
  
    [self.gameOverViewController showEndRoundAnimation];
}
// TableManagerDelegate
-(void) dealTurnComplete
{
    //[self.gameControlViewController show];
    if(!isShowControl) 
    {
        [self.gameRuleProxy requestStatus];
    }
}
// GameControlDelegate
-(void) raiseHandler:(float) percent
{
   
    long money = (long) (percent * myPlayer.Money);
    if(money < callMoney)
    {
            [self.gameRuleProxy doAction:cRaise money:callMoney];
    }
    else 
    {
            [self.gameRuleProxy doAction:cRaise money:money];
    }
}
// GameControlDelegate
-(void) checkHandler:(BOOL) isCheck
{
    //[self.tableManagerViewController dealNextTurn];
    if(isCheck)
    {
        [self.gameRuleProxy doAction:cCheck money:0];
    }
    else 
    {
        [self.gameRuleProxy doAction:cCall money:0];
    }
}
// GameControlDelegate (The same endRound method)
-(void) foldHandler
{
    //[self.gameOverViewController changeMessage:@"You Lose !"];
    //[self.gameOverViewController showEndRoundAnimation];
    [self.gameRuleProxy doAction:cFold money:0];
}
// GameOverDelegate
-(void) endRoundAnimationCallback
{
    [self.gameOverView setHidden:YES];
      NSLog(@"================ Start Next Round ==================");
    if(myPlayer.Money <= 0 || rivalPlayer.Money <= 0)
    {
        //[self.tableManagerViewController startRound];
        //[self.gameRuleProxy startRound];
        [self.gameRuleProxy endGame];
    }
   else 
   {
       [self.tableManagerViewController startRound];
       [self.gameRuleProxy startRound];
   }
}
+(GameViewController*) share
{
    if(instance)
    {
        return instance;
    }
    return NULL;
}
// init assets
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        instance = self;
    }
    return self;
}
// method overrides from BaseViewController
-(void) show
{

   // if(self.playerManagerViewController)
   // {
   //     [self.playerManagerViewController playerAnimation];
  //  }
    if(self.gameRuleProxy) [self.gameRuleProxy startGame];
}
// method overrides from BaseViewController
-(void) hide
{
   
}
// init property
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // init table
    self.tableManagerViewController = [[TableManagerViewController new] autorelease];
    CGRect tableF = [self.tableMangagerView frame];
    [self.tableMangagerView removeFromSuperview];
    self.tableMangagerView = [self.tableManagerViewController view];
    [self.tableMangagerView setFrame:tableF];
    [self.view addSubview:self.tableMangagerView];
    [self.tableManagerViewController setTableCallback:self];
    // init table clock view
    self.tableClockViewController = [[TableClockViewController new] autorelease];
    CGRect tableLF = [self.tableClockView frame];
    [self.tableClockView removeFromSuperview];
    self.tableClockView = [self.tableClockViewController view];
    [self.tableClockView setFrame:tableLF];
    [self.view addSubview:self.tableClockView];
    //[self.tableClockViewController setTableClockCallback:self];
    //init players
    self.playerManagerViewController = [[PlayerManagerViewController new] autorelease];
    CGRect playerF = [self.playerManagerView frame];
    [self.playerManagerView removeFromSuperview];
    self.playerManagerView = [self.playerManagerViewController view];
    [self.playerManagerView setFrame:playerF];
    [self.view addSubview:self.playerManagerView];
    [self.playerManagerViewController setPlayerManagerCallback:self];
    // init game rule proxy
    self.gameRuleProxy = [[GameRuleProxy alloc] init];
    [self.gameRuleProxy setGameRuleProxyCallback:self];
    // init game control
    self.gameControlViewController = [[GameControlViewController new] autorelease];
    CGRect gameCF = [self.gameControlView frame];
    [self.gameControlView removeFromSuperview];
    self.gameControlView = [self.gameControlViewController view];
    [self.gameControlViewController setHandlerCallback:self];
    [self.gameControlView setFrame:gameCF];
    [self.view addSubview:self.gameControlView];
    // init gameover view
    self.gameOverViewController = [[GameOverViewController new] autorelease];
    CGRect gameOF = [self.gameOverView frame];
    [self.gameOverView removeFromSuperview];
    self.gameOverView = [self.gameOverViewController view];
    [self.gameOverViewController setGameOverDelegateCallback:self];
    [self.gameOverView setFrame:gameOF];
    [self.view addSubview:self.gameOverView];
    
    [self.gameControlViewController hide];
    [self.gameOverView setHidden:YES];
    [self.view addSubview:btnExit];
     [self.view addSubview:btnAutoPlay];
    _autoplay = false;
    [btnExit setHidden:YES];
    [self.tableClockViewController hide];
    if(self.gameRuleProxy) [self.gameRuleProxy startGame];
}
// Release property
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [self.playerManagerViewController release];
    [self.playerManagerView release];
    [self.gameControlViewController release];
    [self.gameControlView release];
    [self.tableMangagerView release];
    [self.tableManagerViewController release];
    [self.gameOverView release];
    [self.gameOverViewController release];
    [self.gameRuleProxy release];
    [self.myPlayer release];
}
//Change Orientation of Views
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////